<?php

namespace common\models;

use app\models\AdminLog;
use Yii;

/**
 * This is the model class for table "article".
 *
 * @property string $id
 * @property string $title
 * @property string $author
 * @property string $intro
 * @property string $face
 * @property string $is_link
 * @property string $link
 * @property string $content
 * @property string $photos
 * @property string $created_at
 * @property string $created_by
 * @property string $updated_at
 * @property string $updated_by
 */
class Article extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'article';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['created_at', 'created_by', 'updated_at', 'updated_by'], 'integer'],
            [['is_link', 'content'], 'string'],
            [['title'], 'required'],
            [['title', 'author'], 'string', 'max' => 64],
            [['intro'], 'string', 'max' => 1000],
            [['link'], 'string', 'max' => 255],
            [['link'], 'url', 'defaultScheme' => 'http'],
            ['photos', 'safe'],
            [['face'], 'image', 'extensions' => 'jpeg, jpg, gif, png', 'maxSize' => 1 * 1024 * 1024]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'author' => '作者',
            'intro' => '摘要',
            'face' => '封面',
            'is_link' => '展现方式：1为外链',
            'link' => '外链',
            'content' => '内容',
            'photos' => '组图',
            'created_at' => '创建时间',
            'created_by' => '添加人',
            'updated_at' => '更新时间',
            'updated_by' => '更新人',
        ];
    }

    public function behaviors()
    {
        $path = '/uploads/image/' . date('Ymd') . '/' . time() . '[[pk]].[[extension]]';
        return [
            [
                'class' => '\yiidreamteam\upload\ImageUploadBehavior',
                'attribute' => 'face',
                'filePath' => '@frontend/web' . $path,
                'fileUrl' => $path
            ],
        ];
    }

    public function beforeSave($insert)
    {
        if ($this->isNewRecord) {
            $this->created_at = $this->updated_at = time();
            $this->created_by = $this->updated_by = Yii::$app->user->id;
        } else {
            $this->updated_at = time();
            $this->updated_by = Yii::$app->user->id;
        }
        if ($this->photos) {
            $this->photos = rtrim($this->photos, '|');
            $photos = explode('|', $this->photos);
            $this->photos = '';
            foreach ($photos as $photo) {
                if (file_exists(Yii::getAlias('@frontend/web') . $photo)) {
                    $this->photos = $this->photos . $photo . '|';
                }
            }
            $this->photos = rtrim($this->photos, '|');
        }
        return parent::beforeSave($insert);
    }

    public function afterSave($insert, $changedAttributes)
    {
        parent::afterSave($insert, $changedAttributes);
        if ($_FILES[$this->formName()]['name']['face']) {
            $this->updateAll(['face' => $this->getImageFileUrl('face')], ['id' => $this->id]);
        }
        if ($insert) {
            AdminLog::log("新添素材：" . $this->title, "create");
        } else {
            @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $changedAttributes['face']));
            AdminLog::log("更新素材：旧：" . $changedAttributes['title'] . "；新：" . $this->title);
        }
    }

    public function afterDelete()
    {
        parent::afterDelete();
        @unlink(iconv('UTF-8', 'GB2312', Yii::$aliases['@frontend'] . '/web' . $this->face));
        AdminLog::log("删除素材：" . $this->title, "delete");
    }

    /**
     * @param $post \common\models\Post;
     */
    public static function saveFromPost($post)
    {
        $model = Article::findOne($post->article_id);
        if (!$model) {
            $model = new Article();
        }
        $model->title = $post->title;
        $model->author = $post->author;
        $model->intro = $post->intro;
        $model->face = $post->face;
        $model->photos = $post->photos;
        $model->is_link = $post->is_link;
        $model->link = $post->link;
        $model->content = $post->content;
        if ($model->save()) {
            $post->updateAll(['article_id' => $model->id], ['id' => $post->id]);
        }
    }
}
